<?php
/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */
defined('IN_IA') or exit('Access Denied');
load()->func('file');

$dos = array('display', 'post', 'del');
$do = in_array($do, $dos) ? $do : 'display';

permission_check_account_user('platform_site');
$_W['page']['title'] = '文章管理 - 微官网';
$category = pdo_fetchall("SELECT id,parentid,name FROM ".tablename('site_category')." WHERE uniacid = '{$_W['uniacid']}' ORDER BY parentid ASC, displayorder ASC, id ASC ", array(), 'id');
$parent = array();
$children = array();

function insertArticleStores($article_id,$store_ids)
{
    global $_GPC,$_W;
    if(!empty($store_ids))
    {
        foreach ($store_ids as $key=>$value)
        {
            $attrStorData = array(
                'store_id'=>intval($value),
                'article_id'=>$article_id,
                'uniacid'=>$_W['uniacid']
            );
            $insert_storeattr = pdo_insert('storemanage_storearticle',$attrStorData);
            if(!$insert_storeattr){
                throw new Exception('数据插入失败');
            }
        }
    }
}



function getCheckedBox($id,$ids)
{
    if(!empty($id) && is_array($ids)){
        if(in_array($id,$ids)){
            echo "checked";
        }
    }
}


function getArticleStores($article_id)
{
    global $_W;

    if(!empty($article_id)){
        //注意这里的status=1 代表是店铺正常的标签
        $stores = pdo_fetchall("SELECT store_id FROM " . tablename('storemanage_storearticle') . " 
            WHERE `uniacid`=:uniacid and `article_id`=:article_id and status=1", array(':uniacid'=>$_W['uniacid'],':article_id'=>$article_id),'store_id');

        if(!empty($stores)){
            foreach ($stores as $key=>$value)
            {
                $storeIdsFormat[] = $value['store_id'];
            }
            $storeList = pdo_fetchall("SELECT * FROM " . tablename('storemanage_store') . "
            WHERE `uniacid`=:uniacid and `id` in (".implode(',',$storeIdsFormat).") ", array(':uniacid'=>$_W['uniacid']));
            if(!empty($storeList)){
                $res = $storeList;
            }
            else{
                $res = '';
            }
        }
        else{
            $res = '';
        }

    }
    return $res;
}


if (!empty($category)) {
	foreach ($category as $cid => $cate) {
		if (!empty($cate['parentid'])) {
			$children[$cate['parentid']][] = $cate;
		} else {
			$parent[$cate['id']] = $cate;
		}
	}
}

if ($do == 'display') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 20;
	$condition = '';
	$params = array();
	if (!empty($_GPC['keyword'])) {
		$condition .= " AND `title` LIKE :keyword";
		$params[':keyword'] = "%{$_GPC['keyword']}%";
	}
	
	if (!empty($_GPC['category']['childid'])) {
		$cid = intval($_GPC['category']['childid']);
		$condition .= " AND ccate = '{$cid}'";
	} elseif (!empty($_GPC['category']['parentid'])) {
		$cid = intval($_GPC['category']['parentid']);
		$condition .= " AND pcate = '{$cid}'";
	}
	$list = pdo_fetchall("SELECT * FROM ".tablename('site_article')." WHERE uniacid = '{$_W['uniacid']}' $condition ORDER BY displayorder DESC, edittime DESC, id DESC LIMIT ".($pindex - 1) * $psize.','.$psize, $params);
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('site_article') . " WHERE uniacid = '{$_W['uniacid']}'".$condition, $params);
	$pager = pagination($total, $pindex, $psize);
	template('site/article-display');

} elseif ($do == 'post') {

    //店铺选择
    $storeList = pdo_fetchall("SELECT * FROM " . tablename('storemanage_store') . " 
        WHERE `uniacid`=:uniacid", array(':uniacid'=>$_W['uniacid']));

	$id = intval($_GPC['id']);
    $template = uni_templates();
	$pcate = intval($_GPC['pcate']);
	$ccate = intval($_GPC['ccate']);
	if (!empty($id)) {


        $articleStoreIds = array();
        $articleStores = getArticleStores($id);
        if(!empty($articleStores))
        {
            foreach ($articleStores as $key=>$value)
            {
                $articleStoreIds[] = $value['id'];
            }
        }

        $item = pdo_fetch("SELECT * FROM ".tablename('site_article')." WHERE id = :id" , array(':id' => $id));
		$item['type'] = explode(',', $item['type']);
		$pcate = $item['pcate'];
		$ccate = $item['ccate'];
		if (empty($item)) {
			itoast('抱歉，文章不存在或是已经删除！', '', 'error');
		}
		$key = pdo_fetchall('SELECT content FROM ' . tablename('rule_keyword') . ' WHERE rid = :rid AND uniacid = :uniacid', array(':rid' => $item['rid'], ':uniacid' => $_W['uniacid']));
		if (!empty($key)) {
			$keywords = array();
			foreach ($key as $row) {
				$keywords[] = $row['content'];
			}
			$keywords = implode(',', array_values($keywords));
		}
		$item['credit'] = iunserializer($item['credit']) ? iunserializer($item['credit']) : array();
		if (!empty($item['credit']['limit'])) {
						$credit_num = pdo_fetchcolumn('SELECT SUM(credit_value) FROM ' . tablename('mc_handsel') . ' WHERE uniacid = :uniacid AND module = :module AND sign = :sign', array(':uniacid' => $_W['uniacid'], ':module' => 'article', ':sign' => md5(iserializer(array('id' => $id)))));
			if (is_null($credit_num)) {
				$credit_num = 0;
			}
			$credit_yu = (($item['credit']['limit'] - $credit_num) < 0) ? 0 : $item['credit']['limit'] - $credit_num;
		}
	} else {
		$item['credit'] = array();
		$keywords = '';
	}
	if (checksubmit('submit')) {
		if (empty($_GPC['title'])) {
			itoast('标题不能为空，请输入标题！', '', '');
		}
		$data = array(
			'uniacid' => $_W['uniacid'],
			'iscommend' => intval($_GPC['option']['commend']),
			'ishot' => intval($_GPC['option']['hot']),
			'pcate' => intval($_GPC['category']['parentid']),
			'ccate' => intval($_GPC['category']['childid']),
			'template' => addslashes($_GPC['template']),
			'title' => addslashes($_GPC['title']),
			'description' => addslashes($_GPC['description']),
			'content' => htmlspecialchars_decode($_GPC['content'], ENT_QUOTES),
			'incontent' => intval($_GPC['incontent']),
			'source' => addslashes($_GPC['source']),
			'author' => addslashes($_GPC['author']),
			'displayorder' => intval($_GPC['displayorder']),
			'linkurl' => addslashes($_GPC['linkurl']),
			'createtime' => TIMESTAMP,
			'edittime' => TIMESTAMP,
			'click' => intval($_GPC['click']),
            );

        $data['brandlogo'] = isset($_GPC['brandlogo'])?$_GPC['brandlogo']:'';




		if (!empty($_GPC['thumb'])) {
			if (file_is_image($_GPC['thumb'])) {
				$data['thumb'] = $_GPC['thumb'];
			}
		} elseif (!empty($_GPC['autolitpic'])) {
			$match = array();
			preg_match('/&lt;img.*?src=&quot;?(.+\.(jpg|jpeg|gif|bmp|png))&quot;/', $_GPC['content'], $match);
			if (!empty($match[1])) {
				$url = $match[1];
				$file = file_remote_attach_fetch($url);
				if (!is_error($file)) {
					$data['thumb'] = $file;
					file_remote_upload($file);
				}
			}
		} else {
			$data['thumb'] = '';
		}


        $keyword = str_replace('，', ',', trim($_GPC['keyword']));
		$keyword = explode(',', $keyword);
		if (!empty($keyword)) {
			$rule['uniacid'] = $_W['uniacid'];
			$rule['name'] = '文章：' . $_GPC['title'] . ' 触发规则';
			$rule['module'] = 'news';
			$rule['status'] = 1;
			$keywords = array();
			foreach ($keyword as $key) {
				$key = trim($key);
				if (empty($key)) continue;
				$keywords[] = array(
					'uniacid' => $_W['uniacid'],
					'module' => 'news',
					'content' => $key,
					'status' => 1,
					'type' => 1,
					'displayorder' => 1,
				);
			}
			$reply['title'] = $_GPC['title'];
			$reply['description'] = $_GPC['description'];
			$reply['thumb'] = $data['thumb'];
			$reply['url'] = murl('site/site/detail', array('id' => $id));
		}
				if (!empty($_GPC['credit']['status'])) {
			$credit['status'] = intval($_GPC['credit']['status']);
			$credit['limit'] = intval($_GPC['credit']['limit']) ? intval($_GPC['credit']['limit']) : itoast('请设置积分上限', '', '');
			$credit['share'] = intval($_GPC['credit']['share']) ? intval($_GPC['credit']['share']) : itoast('请设置分享时赠送积分多少', '', '');
			$credit['click'] = intval($_GPC['credit']['click']) ? intval($_GPC['credit']['click']) : itoast('请设置阅读时赠送积分多少', '', '');
			$data['credit'] = iserializer($credit);
		} else {
			$data['credit'] = iserializer(array('status' => 0, 'limit' => 0, 'share' => 0, 'click' => 0));
		}


		if (empty($id)) {
			unset($data['edittime']);
			if (!empty($keywords)) {
				pdo_insert('rule', $rule);
				$rid = pdo_insertid();
				foreach ($keywords as $li) {
					$li['rid'] = $rid;
					pdo_insert('rule_keyword', $li);
				}
				$reply['rid'] = $rid;
				pdo_insert('news_reply', $reply);
				$data['rid'] = $rid;
			}

			pdo_begin();   //新增
            try{
                $stores = $_GPC['store'];
                if(!empty($stores)){
                    //冗余数据 用于搜索
                    $articleStoreMarkIds = implode(',',$stores);
                    $articleStoreMarkInfo = pdo_fetchall("select storename from ".tablename('storemanage_store')."
                        where `uniacid`=:uniacid and `id` in (".$articleStoreMarkIds.")",array(':uniacid'=>$_W['uniacid']));

                    if(!empty($articleStoreMarkInfo)){
                        $articleArticleMark = '|';
                        //文章店铺冗余字段
                        foreach ($articleStoreMarkInfo as $key=>$value)
                        {
                            $articleArticleMark .= $value['storename']."|";
                        }
                        $data['article_stores'] = $articleArticleMark;
                    }

                    //根据store_id集合查询attr_id集合
                    $storeAttrs = pdo_fetchall("select DISTINCT (attr_id) from ".tablename('storemanage_attrstore')."
                        where `uniacid`=:uniacid and `store_id` in (".$articleStoreMarkIds.") and `status`=1",
                        array(':uniacid'=>$_W['uniacid'])
                    );

                    if(!empty($storeAttrs)){
                        foreach ($storeAttrs as $key=>$value)
                        {
                            $storeAttrsIds[] = $value['attr_id'];
                        }
                        $storeAttrMarkIds = implode(',',$storeAttrsIds);
                    }

                    //根据attr_id集合查询attr_name
                    $storeAttrMarks = pdo_fetchall("select * from ".tablename('storemanage_attr')."
                        where `uniacid`=:uniacid and `id` in (".$storeAttrMarkIds.")",array(':uniacid'=>$_W['uniacid']));

                    if(!empty($storeAttrMarks)){
                        $articleAttrMark = array();
                        foreach ($storeAttrMarks as $key=>$value)
                        {

                            $articleAttrMark[$value['key']]= $value['value'];
                        }
                        $data['article_attrs'] = json_encode($articleAttrMark,JSON_UNESCAPED_UNICODE);
                    }

                    /*
                    if(!empty($storeAttrMarks)){
                        $articleAttrMark = '|';
                        foreach ($storeAttrMarks as $key=>$value)
                        {
                            $articleAttrMark .= $value['value']."|";
                        }
                        $data['article_attrs'] = $articleAttrMark;
                    }
                    */
                }
                pdo_insert('site_article', $data);

                $aid = pdo_insertid();
                //文章和店铺的关联
                if($aid)
                {

                    if(!empty($stores))
                    {
                        insertArticleStores($aid,$stores);
                    }
                }else{
                    throw new Exception('添加文章失败');
                }
                pdo_commit();
            }catch (Exception $e){
                pdo_rollback();
                message('添加文章失败','referer','error');
            }
			pdo_update('news_reply', array('url' => murl('site/site/detail', array('id' => $aid))), array('rid' => $rid));
		} else {
			unset($data['createtime']);
			pdo_delete('rule', array('id' => $item['rid'], 'uniacid' => $_W['uniacid']));
			pdo_delete('rule_keyword', array('rid' => $item['rid'], 'uniacid' => $_W['uniacid']));
			pdo_delete('news_reply', array('rid' => $item['rid']));
			if (!empty($keywords)) {
				pdo_insert('rule', $rule);
				$rid = pdo_insertid();

				foreach ($keywords as $li) {
					$li['rid'] = $rid;
					pdo_insert('rule_keyword', $li);
				}

				$reply['rid'] = $rid;
				pdo_insert('news_reply', $reply);
				$data['rid'] = $rid;
			} else {
				$data['rid'] = 0;
				$data['kid'] = 0;
			}
                $stores = $_GPC['store'];
                if(!empty($stores)){
                    //冗余数据 用于搜索
                    $articleStoreMarkIds = implode(',',$stores);
                    $articleStoreMarkInfo = pdo_fetchall("select storename from ".tablename('storemanage_store')."
                        where `uniacid`=:uniacid and `id` in (".$articleStoreMarkIds.")",array(':uniacid'=>$_W['uniacid']));

                    if(!empty($articleStoreMarkInfo)){
                        $articleArticleMark = '|';
                        //文章店铺冗余字段
                        foreach ($articleStoreMarkInfo as $key=>$value)
                        {
                            $articleArticleMark .= $value['storename']."|";
                        }
                        $data['article_stores'] = $articleArticleMark;
                    }

                    //根据store_id集合查询attr_id集合
                    $storeAttrs = pdo_fetchall("select DISTINCT (attr_id) from ".tablename('storemanage_attrstore')."
                        where `uniacid`=:uniacid and `store_id` in (".$articleStoreMarkIds.") and `status`=1",array(':uniacid'=>$_W['uniacid']));

                    if(!empty($storeAttrs)){
                        foreach ($storeAttrs as $key=>$value)
                        {
                            $storeAttrsIds[] = $value['attr_id'];
                        }
                        $storeAttrMarkIds = implode(',',$storeAttrsIds);
                    }

                    //根据attr_id集合查询attr_name
                    $storeAttrMarks = pdo_fetchall("select * from ".tablename('storemanage_attr')."
                        where `uniacid`=:uniacid and `id` in (".$storeAttrMarkIds.")",array(':uniacid'=>$_W['uniacid']));

                    if(!empty($storeAttrMarks)){
                        $articleAttrMark = array();
                        foreach ($storeAttrMarks as $key=>$value)
                        {

                            $articleAttrMark[$value['key']]= $value['value'];
                        }
                        $data['article_attrs'] = json_encode($articleAttrMark,JSON_UNESCAPED_UNICODE);
                    }
                }else{
                    //编辑状态 如果没有选择店铺则置空店铺字段内容以及属性字段内容
                    $data['article_attrs'] = null;
                    $data['article_stores'] = null;
                }
                $updated = pdo_update('site_article', $data, array('id' => $id));
                //文章和店铺的关联
                if($updated)
                {
                    itoast('文章更新成功！', url('site/article/display'), 'success');
                }

		}
		itoast('文章更新成功！', url('site/article/display'), 'success');
	} else {
		template('site/article-post');
	}
} elseif($do == 'del') {
	if (checksubmit('submit')) {
		foreach ($_GPC['rid'] as $key => $id) {
			$id = intval($id);
			$row = pdo_get('site_article', array('id' => $id, 'uniacid' => $_W['uniacid']));
			
			if (empty($row)) {
				itoast('抱歉，文章不存在或是已经被删除！', '', '');
			}

			if (!empty($row['rid'])) {
				pdo_delete('rule', array('id' => $row['rid'], 'uniacid' => $_W['uniacid']));
				pdo_delete('rule_keyword', array('rid' => $row['rid'], 'uniacid' => $_W['uniacid']));
				pdo_delete('news_reply', array('rid' => $row['rid']));
			}
			pdo_delete('site_article', array('id' => $id, 'uniacid'=>$_W['uniacid']));
		}
		itoast('批量删除成功！', referer(), 'success');
	} else {
		$id = intval($_GPC['id']);
		$row = pdo_fetch("SELECT id,rid,kid,thumb FROM ".tablename('site_article')." WHERE id = :id", array(':id' => $id));
		
		if (empty($row)) {
			itoast('抱歉，文章不存在或是已经被删除！', '', '');
		}

		if (!empty($row['rid'])) {
			pdo_delete('rule', array('id' => $row['rid'], 'uniacid' => $_W['uniacid']));
			pdo_delete('rule_keyword', array('rid' => $row['rid'], 'uniacid' => $_W['uniacid']));
			pdo_delete('news_reply', array('rid' => $row['rid']));
		}
		if (pdo_delete('site_article', array('id' => $id,'uniacid'=>$_W['uniacid']))){
			itoast('删除成功！', referer(), 'success');
		} else {
			itoast('删除失败！', referer(), 'error');
		}
	}
}